<template>
  <div>
    <div class="model_header">
      <div>联系人</div>
      <div>{{ frame.nickname }}</div>
    </div>
    <div class="model_main" v-if="state">
      <div class="model_main_left">
        <div
          :class="
            index == active
              ? 'liaotian_active model_main_left_list'
              : 'model_main_left_list'
          "
          v-for="(item, index) in sideList"
          :key="index"
          @click="liaotianList(index)"
        >
          <div>
            <img :src="item.headImg" alt="" />
          </div>
          <div>
            <div class="div-flex">
              <p>{{ item.nickname }}</p>
              <h5>{{ item.createTime | getStandardDate }}</h5>
            </div>
            <div class="div-flex">
              <div class="msg">{{ item.msg || "打个招呼吧~" }}</div>
              <div class="quan" v-if="item.unReadNum > 0">
                {{ item.unReadNum }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="model_main_right">
        <div id="liaotian" class="model_main_right_top">
          <div v-if="msgList.length > 0">
            <!-- 对方 -->
            <!-- <div class="side">
              <div><img :src="frame.headImg" alt="" /></div>
              <div>{{ frame.msg || "打个招呼吧~" }}</div>
            </div> -->
            <!-- 自己 -->
            <div
              :class="
                el.receiverId == $getStorage('userinfo').id ? 'side' : 'mySide'
              "
              v-for="(el, index) in msgList"
              :key="index"
            >
              <p class="model_main_right_time">
                {{ el.createTime | getStandardDate }}
              </p>
              <div class="img"><img :src="el.createHeadImg" alt="" /></div>
              <div class="msg">{{ el.content }}</div>
            </div>
          </div>
        </div>
        <div class="model_main_right_bottom">
          <el-form ref="form" :model="form" label-width="80px">
            <el-input
              type="textarea"
              v-model="form.text"
              placeholder="请输入内容..."
            ></el-input>
          </el-form>
        </div>
        <div class="model_main_right_bottom_btn">
          <el-button type="primary" @click="btnSend">发送</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: ["herInfo"],
  inject: ["websocketsend", "reload"],
  data() {
    return {
      stautsBar: true,
      //我的对话
      mySide: [],
      //对方的对话
      msgList: [],
      active: 0,
      //聊天框的标题和话语
      frame: { msgList: [],page:1 },
      partChart: "",
      form: { text: "" },
      state: true, //用于刷新

    };
  },
  computed: {
    //联系人列表
    sideList(obj) {
      return obj && this.$store.state.sideList;
    },
  },
  watch: {
    msgList: {
      handler(newData, old) {
        
        this.$nextTick(()=>{
          var dom = document.getElementById("liaotian");
          if (this.frame.page == 1) {
            dom.scrollTop = dom.scrollHeight;
          } else {
            dom.scrollTop = 0;
          }
        })
          
      },
    },
  },
  filters: {
    getStandardDate(time) {
      var date = new Date(time); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + "-";
      var M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var h =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var m =
        date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      var s =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return Y + M + D + " " + h + m; //时分秒可以根据自己的需求加上
    },
  },
  mounted() {
     //监听滚动条位置
    let dom = document.getElementById("liaotian");
    dom.addEventListener("scroll", function () {
      if (dom.scrollTop == 0&&this.frame) {
        this.frame.page = this.frame.page + 1;
        this.getDetailNoti(this.herInfo.id, this.frame.page);
      }
    });
    //生成聊天联系人数组
    this.initNoti();
    //私信
    if (this.herInfo) {
      //已经存在于联系人数组
      if (
        this.sideList.find((item) => {
          return item.receiverId == this.herInfo.id;
        })
      ) {
        //修改激活项
        let ind = this.sideList.findIndex((item, index) => {
          return item.receiverId == this.herInfo.id;
        });
        this.active = ind;
        this.getDetailNoti(this.herInfo.id, this.frame.page);
      } else {
        let arr = this.sideList;
        arr.unshift({
          headImg: this.herInfo.headImg,
          nickname: this.herInfo.nickname,
          unReadNum: 0,
          createTime: new Date().getTime(),
          msg: "",
          receiverId: this.herInfo.id,
        });
        this.active = 0;
        this.$store.commit("setList", arr);
        //当前对话内容
        this.frame = { ...this.sideList[0], page: 1 };
        this.msgList = [
          {
            content: "打个招呼吧~",
            receiverId: this.$getStorage("userinfo").id,
            createTime: new Date().getTime(),
            createHeadImg: this.herInfo.headImg,
          },
        ];
      }
    } else {
      this.getDetailNoti(this.frame.receiverId, this.frame.page);
    }
  },
  
  methods: {
    //发送信息
    btnSend() {
      if (this.form.text.trim().length !== 0) {
        this.websocketsend({
          receiverId: this.frame.receiverId,
          content: this.form.text,
        });
        //获取详情
        this.getDetailNoti(this.frame.receiverId, this.frame.page);
        //发送内容
        let msg = this.form.text;
        this.form.text = "";
        //该联系人已经存在
        if (
          this.sideList.find((item) => {
            return item.receiverId ==this.frame.receiverId;
          })
        ) {
          //修改时间和msg
          let data = this.sideList.map((item) => {
            if (item.receiverId == this.frame.receiverId) {
              item.msg = msg;
              item.createTime = new Date().getTime();
            }
            return item;
          });
          // this.$store.commit("setList", data);
        } else {
          //不存在该联系人
          let arr = this.sideList;
          arr.unshift({
            headImg: this.herInfo.headImg,
            nickname: this.herInfo.nickname,
            unReadNum: 0,
            createTime: new Date().getTime(),
            msg: msg,
            receiverId: this.herInfo.id,
          });
          this.active = 0;
          this.$store.commit("setList", arr);
        }
      } else {
        this.$message.warning("没有内容");
      }
    },
    liaotianList(index) {
      this.active = index;
      this.frame = this.sideList[index];
      this.getDetailNoti(this.frame.receiverId, this.frame.page);

      let dom = document.getElementById("liaotian");
      dom.scrollTop = dom.scrollHeight;
    },
    //初始化联系人数据
    initNoti() {
      this.active = 0;
      this.frame = { ...this.sideList[0], page: 1 };
    },
    //根据id查询聊天信息
    getDetailNoti(id, page) {
      this.$axios({
        method: "post",
        url: "/message/selectByHistory",
        data: this.$qs.stringify({
          receiveId: id,
          page: page,
          size:50
        }),
      }).then((res) => {
        console.log(res);
        if (res.code != "200") {
          this.$message.error(res.msg);
        } else {
          this.frame.msgList = res.data;
          this.frame.page=1
          this.msgList = res.data.reverse();

          //全部已读
          if (this.frame.unReadNum > 0) {
            this.readMsg(id);
          }
          let dom = document.getElementById("liaotian");
          if (this.frame.page == 1) {
            dom.scrollTop = dom.scrollHeight;
          } else {
            dom.scrollTop = 0;
          }
        }
      });
    },
    readMsg(id) {
      this.$axios({
        method: "post",
        url: "/message/markRead",
        data: this.$qs.stringify({
          createId: id,
        }),
      }).then((res) => {
        console.log(res);
        if (res.code != "200") {
          this.$message.error(res.msg);
        } else {
          //修改未读数量为0
          let data = this.sideList.map((item) => {
            if (item.receiverId == id) {
              item.unReadNum = 0;
            }
            return item;
          });
          this.$store.commit("setList", data);
          let dom = document.getElementById("liaotian");
          dom.scrollTop = dom.scrollHeight;
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
@import url("../../less/myhome.less");
.div-flex {
  display: flex;
  justify-content: space-between;
  h5 {
    font-weight: 400;
  }
  .quan {
    width: 20px;
    height: 20px;
    background-color: #f33;
    border-radius: 50%;
    line-height: 20px;
    text-align: center;
    color: #fff;
    font-size: 12px !important;
  }
  .msg {
    letter-spacing: 1px;
  }
}
</style>